package edu.buaa.act.travel.m.tpdl;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class CityActivity extends TpdlActivity {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public static final String TYPE = "city";

	@Override
	public String toString() {
		String des = "";
		for (Activity a : subactivities) {
			des += a.toString() + "\n";
		}
		return des;
	}

	@Override
	protected JSONObject toJSONObject() {
		JSONObject o = super.toJSONObject();
		try {
			o.put("type", TYPE);
			JSONArray array = new JSONArray();
			for (Activity a : subactivities) {
				if (a instanceof StartActivity || a instanceof EndActivity) {
					continue;
				}
				array.put(a);
			}
			o.put("activities", array);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return o;
	}

	@Override
	public void fromJSON(JSONObject j) throws JSONException {
		super.fromJSON(j);
		
		ActivityFactory factory = ActivityFactory.getInstance();
		
		JSONArray array = j.getJSONArray("activities");
		// 添加开始活动
		this.addSubActivity(new StartActivity(this.id+"start"));
		
		for (int i = 0; i < array.length(); i++) {
			JSONObject o = array.getJSONObject(i);
			Activity a = factory.create(o.getString("type"));
			a.fromJSON(o);
			this.addSubActivity(a);
		}
		// 添加结束活动
		this.addSubActivity(new EndActivity(this.id+"end"));
		
		for (int i = 0; i < subactivities.size() - 1; i++) {
			Flow flow = subactivities.get(i).createOutFlow("jsonflow");
			subactivities.get(i+1).addIncomingFlow(flow);
		}
	}
}
